package com.mamingchao.basic.arraysort.mergesort;

/**
 * Created by mlamp on 2024/6/18.
 */
public class MergeSortNew {

    public static void main(String[] args) {
        int[] arr = {1,3,5,7,9,2,4,6,8};
//        int[] arr = {1,3,5,7,2,4,6,8};
       recursion(arr, 0 ,arr.length-1);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }
    }


    private static void  recursion(int[] arr, int L, int R){

        if (L == R)
            return;

        int mid = L + ((R-L) >> 1);

        recursion(arr, L, mid);
        recursion(arr, mid + 1, R);

        mergeSortWorker(arr, L, mid, R);

    }


    private static void mergeSortWorker(int[] arr, int L, int mid, int R){
        int[] help = new int[R - L + 1];
        int i = 0;
        int leftIndex = L;
        int rightIndex = mid + 1;

        while (leftIndex <=mid && rightIndex <= R) {
            help[i++] = arr[leftIndex] <= arr[rightIndex] ? arr[leftIndex++ ] : arr[rightIndex++];
        }

        while (leftIndex <=mid) {
            help[i++] =  arr[leftIndex++ ];
        }

        while (rightIndex <=R) {
            help[i++] =  arr[rightIndex++ ];
        }

        for (int j = 0; j < help.length; j++) {
            arr[L + j] = help[j];
        }
    }

}
